package com.qaml.mes.device.domain.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.earth.page.PageResponse;
import com.earth.user.AuthSsoContext;
import com.qaml.mes.device.api.DayOffService;
import com.qaml.mes.device.dao.DayOffConfigDO;
import com.qaml.mes.device.domain.convert.DayOffConvert;
import com.qaml.mes.device.dto.dayoff.DayOffIdReqDTO;
import com.qaml.mes.device.dto.dayoff.DayOffPageReqDTO;
import com.qaml.mes.device.dto.dayoff.DayOffSaveReqDTO;
import com.qaml.mes.device.enums.DayOffType;
import com.qaml.mes.device.enums.DeletedEnum;
import com.qaml.mes.device.repository.DayOffRepository;
import com.qaml.mes.device.utils.IdGenerateUtils;
import com.qaml.mes.device.vo.dayoff.DayOffRespVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service
public class DayOffServiceImpl implements DayOffService {

    @Autowired
    private DayOffRepository dayoffRepository;

    @Override
    public String saveOrUpdate(DayOffSaveReqDTO reqDTO) {
        DayOffConfigDO configDO = DayOffConvert.INSTANCE.reqDTO2DO(reqDTO);
        configDO.setDayOffTypeDesc(DayOffType.getMessageByCode(configDO.getDayOffType()));
        if (Objects.isNull(configDO.getId())) {
            configDO.setId(IdGenerateUtils.getId());
            configDO.setTenantId(AuthSsoContext.tenantId());
            dayoffRepository.save(configDO, false);
        } else {
            dayoffRepository.save(configDO, true);
        }
        return String.valueOf(configDO.getId());
    }


    @Override
    public PageResponse<DayOffRespVO> pageList(DayOffPageReqDTO reqDTO) {
        DayOffConfigDO configDO = DayOffConvert.INSTANCE.pageReqDTO2DO(reqDTO);
        if (Objects.isNull(configDO)) {
            configDO = new DayOffConfigDO();
        }
        configDO.setTenantId(AuthSsoContext.tenantId());
        IPage<DayOffConfigDO> pageResult = dayoffRepository.page(reqDTO.getPage(), reqDTO.getPageSize(), configDO);
        if (!CollectionUtils.isEmpty(pageResult.getRecords())) {
            List<DayOffRespVO> dayOffRespVOS = DayOffConvert.INSTANCE.dos2pageVos(pageResult.getRecords());
            return new PageResponse<>(pageResult.getTotal(), dayOffRespVOS, reqDTO);
        }
        return new PageResponse<>(pageResult.getTotal(), null, reqDTO);
    }

    @Override
    public Boolean deleted(DayOffIdReqDTO reqDTO) {
        DayOffConfigDO configDO = new DayOffConfigDO();
        configDO.setId(reqDTO.getId());
        configDO.setIsDeleted(DeletedEnum.YES.getCode());
        dayoffRepository.save(configDO, true);
        return Boolean.TRUE;
    }
}
